import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { ref } from "vue";

//1.创建axios实例
const request = axios.create({
  //接口
  baseURL: "/api",
  //超时时间
  timeout: 3000,
});

//2.请求拦截器
request.interceptors.request.use((config) => {
  let token = sessionStorage.getItem("token");
  if (token) {
    config.headers["token"] = token;
  }
  //加载loading
  addLoading();
  return config;
});

//3.响应拦截器
request.interceptors.response.use(
  (res) => {
    //取消加载loading
    cancelLoading();

    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = res.data.msg;
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }

    if (code == 304) {
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    }

    return res;
  },
  (error) => {
    cancelLoading();
    if (error && error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          ElMessage.error("请求错误");
          break;
        case 401:
          ElMessage.error("未授权，请重新登录");
          break;
        case 403:
          ElMessage.error("登录过期，请重新登录");
          break;
        case 404:
          ElMessage.error("请求错误，未找到相应的资源");
          break;
        case 408:
          ElMessage.error("请求超时");
          break;
        case 500:
          ElMessage.error("服务器错误");
          break;
        case 504:
          ElMessage.error("网络超时");
          break;
        default:
          ElMessage.error("请求失败");
      }
    } else {
      if (JSON.stringify(error).includes("timeout")) {
        error.code = "TIMEOUT";
        error.message = "服务器响应超时";
      }
    }
    return Promise.reject(error);
  }
);

//4.配置全局loading
let loadCount = 0;
let loadingInstance = ref(null);

//加载loading
const addLoading = () => {
  loadCount++;
  if (loadCount == 1) {
    loadingInstance.value = ElLoading.service({
      fullscreen: false,
      text: "请求中...",
      background: "rgb(0,0,0,0)",
    });
  }
};

//取消加载loading
const cancelLoading = () => {
  loadCount--;
  if (loadCount == 0) {
    loadingInstance.value.close();
  }
};

//导出axios实例
export default request;
